
<template>
    <el-dialog :close-on-click-modal="false"  title="地图绘制" append-to-body class="map-dialog" :visible.sync="mapVisible" width="90%" top="5vh"
        @close="closeMapDialog">
        <baidu-map v-if="mapVisible" id="map" class="map" :center="center" :zoom="zoom" :scroll-wheel-zoom="true"
            map-type="BMAP_HYBRID_MAP" @mousemove="syncPolyline" @click="paintPolyline" @rightclick="newPolyline">
            <bm-control v-if="isShowCloseBtn">
                <div class="header_div">
                    <div class="paint_btn">
                        <el-button type="primary" @click="toggle('polyline')">{{ polyline.editing ? "停止绘制" :
                            initPolygon.length > 0 ? '重新绘制' : "开始绘制"
                        }}</el-button>
                        <el-button type="primary" @click="cancelCheck">取消选区</el-button>
                    </div>
                    <div class="search_input">
                        <bm-auto-complete v-model="keyword" :sug-style="{ zIndex: 999999 }">
                            <el-input v-model="keyword" type="text" placeholder="请输入地名关键字" clearable>
                                <i slot="prefix" class="el-input__icon el-icon-search"></i>
                            </el-input>
                        </bm-auto-complete>
                    </div>
                </div>
            </bm-control>
            <bm-local-search :location="''" :keyword="keyword" :select-first-result="false" :auto-viewport="true"
                :panel="false" @searchcomplete="searchcomplete" />
            <bm-polyline v-for="(path, index) in polyline.paths" :key="index" stroke-color="#f8c901" :path="path"
                @lineupdate="openMap" />
            <bm-marker v-for="(item, index) in groupLngLatArr" :key="index + 9999999" :position="{
                lng: item.center.lng - 0.000003,
                lat: item.center.lat - 0.000043
            }" :dragging="false">
                <bm-label :content="item[0].title.facilityName" :label-style="labelStyle"
                    :offset="{ width: -5, height: 15 }" @click="infoMultipleOpen(item)" />
            </bm-marker>
            <div v-for="(items, indexs) in groupLngLatArr" :key="indexs + 100000">
                <bm-polygon :path="items" stroke-color="#03F5EC" fill-color="#00fff6" :stroke-opacity="1"
                    :fill-opacity="0.2" :stroke-weight="3" />
            </div>
            <div v-for="(items, indexs) in initLngLatArr" :key="indexs + 1000000">
                <bm-polygon :path="items" stroke-color="#f9c800" fill-color="#f9c800" :stroke-opacity="1"
                    :fill-opacity="0.2" :stroke-weight="3" />
            </div>
        </baidu-map>
        <template #footer>
            <span class="dialog-footer">
                <el-button class="zh-button-one" @click="closeMapDialog">取 消</el-button>
                <el-button class="zh-button-two" v-if="isShowCloseBtn" type="primary" @click="confirmSelect">确 定</el-button>
            </span>
        </template>
    </el-dialog>
</template>

<script>
export default {
    name: "DivideManage",
    props: {
        mapVisible: {
            type: Boolean,
            default: () => {
                return false
            }
        },
        facilityId: {
            type: Number,
            default: () => {
                return -1
            }
        },
        isShowCloseBtn: {
            type: Boolean,
            default: () => {
                return true
            }
        },
        initPolygon: {
            type: Array,
            default: () => {
                return []
            }
        },
    },
    data() {
        return {
            // 区域是否可修改
            obj: {
                name: ""
            },
            center: { lng: 120.230648, lat: 30.811543 },
            polyline: {
                editing: false,
                paths: []
            },
            polyedit: false,
            // 地图相关值
            zoom: 18,
            lessee: "",
            // 土地名称
            facilityName: "",
            facilityTypeNo: "",
            facilitylist: [],
            topitemtypeid: false,
            // 地图 搜索
            keyword: "",
            // 经纬度数组
            facilityPointList: [],
            // 设施类型
            facilityTypeList: [],
            // 选中的数据项数组 ID组成
            facilityIdList: [],
            // 展示经纬度数组
            polygonPath: [],
            // 农业类型
            Baselist: [],
            // 地图点 label 样式
            labelStyle: {
                color: "#fffff0",
                fontSize: ".75rem",
                borderRadius: ".5rem",
                border: "none",
                backgroundColor: "#00a1c2",
                padding: ".1875rem",
                opacity: ".8",
                letterSpacing: ".125rem",
                transform: "translateX(-32%)"
            },
            // 单位
            unitList: [],
            unitLists: [],
            groupLngLatArr: [],
            initLngLatArr: [],
            showInitPolygon: false,
            initPolygonObj: {},
            lesseeList: [],
            facilityNo: "",
            lesseeNo: "",
            facilityStatus: true,
            periodYears: "",
            periodVisible: false,
            title: "废弃设施",
            facilityStatusObj: {}
        };
    },
    watch: {
        mapVisible(v) {
            v && this.FacilPointList();
        }
    },
    computed: {
        allFacility() {
            return this.$store.state.initData.allFacility || [];
        }
    },
    created() {
    },
    methods: {
        // 计算多边形中心点
        getCenterPoint(data) {
            let lng = 0.0;
            let lat = 0.0;
            for (let point of data) {
                lat += point["lat"];
                lng += point["lng"];
            }
            lng = lng / data.length + 0.000084;
            lat = lat / data.length + 0.000014;
            return { lng: lng, lat: lat };
        },
        searchcomplete(e) {
            if (e) {
                this.zoom = 18;
                this.center = {
                    lat: e.Kr[0].pointN.lat,
                    lng: e.Kr[0].pointN.lng
                };
            }
        },
        initMapData() {
            this.facilityPointList = this.initPolygon;
            let lngLatArr = [];
            this.initLngLatArr = [];
            this.initPolygon.forEach(item => {
                const obj = {};
                obj["lng"] = item.axisY;
                obj["lat"] = item.axisX;
                lngLatArr.push(obj);
            });
            if (lngLatArr.length > 0) {
                this.initLngLatArr.push(lngLatArr);
            }
            console.log(this.initLngLatArr)
        },
        // 查询所有设施信息
        async FacilPointList() {
            console.log(this.allFacility)
            let resp = this.allFacility
            this.groupLngLatArr = [];
            this.list = resp;
            let lngLatAll = [];
            this.list.forEach(itemthree => {
                if (itemthree.facilityPointList && Number(itemthree.facilityId) !== Number(this.facilityId)) {
                    let lngLatArr = [];
                    let facilityGroupArr = itemthree.facilityPointList;
                    facilityGroupArr.forEach(item => {
                        const obj = {};
                        obj["lng"] = item.axisY;
                        obj["lat"] = item.axisX;
                        obj["title"] = itemthree;
                        lngLatArr.push(obj);
                    });
                    this.groupLngLatArr.push(lngLatArr);
                    this.groupLngLatArr.forEach(item => {
                        item["center"] = this.getCenterPoint(item);
                    });
                    lngLatAll = this.groupLngLatArr[0];
                }
            });
            this.initMapData()
            console.log(this.groupLngLatArr)
            this.$nextTick(() => {
                if (lngLatAll.length === 0) return;
                this.center = {
                    lng: lngLatAll[0].lng,
                    lat: lngLatAll[0].lat
                };
                if (this.groupLngLatArr.length > 100) {
                    this.zoom = 16;
                    this.labelStyle.fontSize = ".75rem";
                } else if (
                    this.groupLngLatArr.length > 60 &&
                    this.groupLngLatArr.length < 100
                ) {
                    this.zoom = 17;
                    this.labelStyle.fontSize = ".875rem";
                } else if (
                    this.groupLngLatArr.length > 30 &&
                    this.groupLngLatArr.length < 60
                ) {
                    this.zoom = 18;
                    this.labelStyle.fontSize = "1rem";
                    this.labelStyle.transform = "translateX(-15%)";
                } else if (this.groupLngLatArr.length < 30) {
                    this.zoom = 18;
                    this.labelStyle.fontSize = "1.0625rem";
                    this.labelStyle.transform = "translateX(0%)";
                }
            });
        },
        // 地图绘制模块
        toggle(name) {
            this[name].editing = !this[name].editing;
            if (this[name].editing) {
                this.initLngLatArr = [];
            }
        },
        syncPolyline(e) {
            if (!this.polyline.editing) {
                return;
            }
            const { paths } = this.polyline;
            if (!paths.length) {
                return;
            }
            const path = paths[paths.length - 1];
            if (!path.length) {
                return;
            }
            if (path.length === 1) {
                path.push(e.point);
            }
            this.$set(path, path.length - 1, e.point);
        },
        newPolyline(e) {
            if (!this.polyline.editing) {
                return;
            }
            const { paths } = this.polyline;
            if (!paths.length) {
                paths.push([]);
            }
            const path = paths[paths.length - 1];
            path.pop();
            if (path.length) {
                paths.push([]);
            }
        },
        paintPolyline(e) {
            if (!this.polyline.editing) {
                this.formData.axisY = e.point.lng;
                this.formData.axisX = e.point.lat;
                return;
            }
            this.initLngLatArr = [];
            const { paths } = this.polyline;
            !paths.length && paths.push([]);
            paths[paths.length - 1].push(e.point);
        },
        // 打开地图dialog
        openMap() {
            this.FacilPointList();
        },
        // 关闭地图dialog
        closeMapDialog() {
            this.polygonPath = [];
            this.polyline.paths = [];
            this.polyline.editing = false;
            this.center = { lng: 120.230648, lat: 30.811543 };
            this.$emit('closeMapDialog', this.facilityPointList);
        },
        // 取消选取
        cancelCheck() {
            this.polyline.paths = [];
            this.polygonPath = [];
        },
        // 确认选取
        confirmSelect() {
            this.facilityPointList = [];
            if (this.polyline.paths[0]) {
                this.polyline.paths[0].forEach((item, index) => {
                    const obj = {};
                    obj["axisX"] = item.lat;
                    obj["axisY"] = item.lng;
                    obj["sort"] = index;
                    obj["type"] = 0; // 0地图， 1图片
                    this.facilityPointList.push(obj);
                });
            }
            this.closeMapDialog()
            console.log(this.facilityPointList)
        }
    }
};
</script>
<style lang="scss" scoped>
.map {
    width: 100%;
    height: calc(100vh - 300px);
}

.header_div {
    display: flex;
    justify-content: flex-start;
    padding: 10px;

    .search_input {
        margin-left: 10px;
    }
}
</style>